package vip.bblog.oauth2.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vip.bblog.common.entity.BblogException;
import vip.bblog.common.utils.BaseResult;

import java.util.List;

/**
 * 异常处理
 *
 * @ClassName: ExceptionHandlerAdvice
 * @Description: 异常处理
 * @author: yuyong
 */
@RestControllerAdvice
public class ExceptionHandlerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);

    @ExceptionHandler({IllegalArgumentException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResult<String> badRequestException(IllegalArgumentException exception) {
        return new BaseResult<>(HttpStatus.BAD_REQUEST.value(), exception.getMessage(), exception.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResult<String> methodArgumentNotValidException(MethodArgumentNotValidException exception) {
        List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
        StringBuilder errors = new StringBuilder();
        allErrors.forEach(a -> {
            errors.append(a.getDefaultMessage()).append(";");
        });
        return new BaseResult<>(HttpStatus.BAD_REQUEST.value(), errors.toString(), errors.toString());
    }

    @ExceptionHandler({BblogException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResult<String> badRequestException(BblogException exception) {
        return new BaseResult<>(HttpStatus.BAD_REQUEST.value(), exception.getMessage(), exception.getMessage());
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResult<String> exception(Throwable throwable) {
        logger.error("系统异常", throwable);
        return new BaseResult<>(HttpStatus.BAD_REQUEST.value(), throwable.getMessage(), throwable.getMessage());
    }

}
